package dialog;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.lanhai.model.Agv;
import com.lanhai.model.Park;
import com.lanhai.utils.DialogUtils;

import application.Main;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.ListView;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * 任务列表
 * @author liangmin
 *
 */
public class CommandListDialog {

//	private static final Logger logger = Logger.getLogger(JobListDialog.class);
	private Main main;
	@FXML
	private Button search;
	@FXML
	private Button export;
	@FXML
	private ListView<String> inputList;
	@FXML
	private ListView<String> outputList;
	@FXML
	private RadioButton rAgv;
	@FXML
	private RadioButton rMw;
//	@FXML
//	private RadioButton rFlow;
//	@FXML
//	private RadioButton rCharger;
	@FXML
	private ComboBox<Object> client;
	@FXML
	private DatePicker sDate;
	@FXML
	private TextField beginTime;
	@FXML
	private TextField endTime;
	private ToggleGroup tg;
	private ObservableList<Object> clientList;
	
	public void init(Main main) {
		this.main = main;
		tg = new ToggleGroup();
		rAgv.setToggleGroup(tg);
		rAgv.setSelected(true);
		rMw.setToggleGroup(tg);
		//rCharger.setToggleGroup(tg);
		//rFlow.setToggleGroup(tg);
		refreshClientList();
    	tg.selectedToggleProperty().addListener(new ChangeListener<Toggle>(){
			@Override
			public void changed(ObservableValue<? extends Toggle> changed, Toggle oldVal, Toggle newVal){
				refreshClientList();
			}
		});	
    	
    	search.setOnAction((ActionEvent t) -> {
    		RadioButton rb = (RadioButton)tg.getSelectedToggle();
    		Map<String, Object> params = new HashMap<String, Object>();
    		if(client.getValue() == null){
    			DialogUtils.show("请选择设备！");
    			return;
    		}
    		if(rb.getId().equals("rAgv")){
    			Agv agv = (Agv)client.getValue();
    			params.put("clientNo", agv.getId());
    			params.put("clientType", "AGV");
    		}else if(rb.getId().equals("rMw")){
    			Park park = (Park)client.getValue();
    			params.put("clientNo", park.getName());
    			params.put("clientType", "Park");
    		}else{
    			
    		}
    		if(sDate.getValue() != null && beginTime != null && endTime != null){
    			params.put("beginTime", sDate.getValue() + " " + beginTime.getText() + ":00");
    			params.put("endTime", sDate.getValue() + " " + endTime.getText() + ":59");
    		}
    		params.put("type", "log");
    		params.put("path", "search");
    		params.put("noPopup", "true");
    		JSONObject jo = main.httpRequest(params);
    		if(jo != null){
        		JSONArray inputLog = jo.getJSONArray("inputLog");
        		JSONArray outputLog = jo.getJSONArray("outputLog");
        		if(inputLog.size() > 0){
            		ObservableList<String> iList = FXCollections.observableArrayList();
            		for(int i=0; i<inputLog.size(); i++){
            			JSONObject obj = inputLog.getJSONObject(i);
            			String timeStr = obj.getString("inputTime")==null? "":obj.getString("inputTime");
            			if(timeStr.length() > 11){
            				timeStr = timeStr.substring(11);
            			}
            			String str = obj.getString("data") + " | " + obj.getString("note")
            				+ " | " + timeStr;
            			iList.add(str);
            		}
            		inputList.setItems(iList);   			
        		}else{
        			inputList.getItems().clear();
        		}
        		       		
        		if(outputLog.size() > 0){
        			ObservableList<String> oList = FXCollections.observableArrayList();
            		for(int j=0; j<outputLog.size(); j++){
            			JSONObject obj = outputLog.getJSONObject(j);
            			String timeStr = obj.getString("outputTime");
            			String str = obj.getString("data") + " | " + obj.getString("note")
            				+ " | " + timeStr.substring(11);
            			oList.add(str);    			
            		}
            		outputList.setItems(oList);    
        		}else{
        			outputList.getItems().clear();
        		}
    		}
		});	
    	
    	/**
    	 * 导出数据
    	 */
    	export.setOnAction((ActionEvent t) -> {
    		RadioButton rb = (RadioButton)tg.getSelectedToggle();
    		Map<String, Object> params = new HashMap<String, Object>();
    		if(client.getValue() == null){
    			DialogUtils.show("请选择设备！");
    			return;
    		}
    		if(rb.getId().equals("rAgv")){
    			Agv agv = (Agv)client.getValue();
    			params.put("clientNo", agv.getId());
    			params.put("clientType", "AGV");
    		}else if(rb.getId().equals("rMw")){
    			Park park = (Park)client.getValue();
    			params.put("clientNo", park.getName());
    			params.put("clientType", "Park");
    		}else{
    			
    		}
    		if(sDate.getValue() != null && beginTime != null && endTime != null){
    			params.put("beginTime", sDate.getValue() + " " + beginTime.getText() + ":00");
    			params.put("endTime", sDate.getValue() + " " + endTime.getText() + ":59");
    		}
    		params.put("type", "log");
    		params.put("path", "search");
    		params.put("noPopup", "true");
    		JSONObject jo = main.httpRequest(params);
    		if(jo != null){
        		JSONArray inputLog = jo.getJSONArray("inputLog");
        		JSONArray outputLog = jo.getJSONArray("outputLog");
        		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        		if(inputLog.size() > 0){
            		//输出到csv文件
        			String currentTime = sdf.format(new Date());
        			String path = "d:/ads/logs/inputLog_" + currentTime + ".CSV";
        			imp2cvs(path, inputLog);
        		}
        		       		
        		if(outputLog.size() > 0){
        			//输出到csv文件
        			String currentTime = sdf.format(new Date());
        			String path = "d:/ads/logs/outputLog_" + currentTime + ".CSV";
        			imp2cvs(path, outputLog);        			
        		}
        		if(inputLog.size() == 0 && outputLog.size() == 0){
        			DialogUtils.show("没有匹配的数据!", "提示", main.logo);
        		}
    		}
    		DialogUtils.show("导出日志完成!", "提示", main.logo);
    	});
		
	}
	
	/**
	 * 输出日志到CVS文件
	 * @param path
	 * @param dataList
	 */
	public void imp2cvs(String path, JSONArray dataList){
		try{
			File csv = new File(path);
			if(!csv.exists()){
				csv.createNewFile();
			}
			//BufferedWriter bw = new BufferedWriter(new FileWriter(csv,true));
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csv), "GBK"));
			JSONObject json = dataList.getJSONObject(0);
			Iterator<?> headerkeys = json.keys();
			String headStr = "";
			while (headerkeys.hasNext()) {
				headStr += headerkeys.next() + ",";
			}
			headStr = headStr.substring(0, headStr.length() - 1);
			bw.write(headStr); 
			bw.newLine();
			for(int i=0; i<dataList.size(); i++){
				JSONObject jo = dataList.getJSONObject(i);
				String val = "";
				Iterator<?> keys = jo.keys();
				while (keys.hasNext()) {
					headStr = (String) keys.next();
					String vStr = jo.getString(headStr);
					vStr = vStr.replaceAll(",", "_");
					val = val + vStr + ",";
				}
				val = val.substring(0, val.length()-1);
				bw.write(val);
				bw.newLine();					
			}	
			bw.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}	
	
	public void refreshClientList(){
		RadioButton rb = (RadioButton)tg.getSelectedToggle();
		clientList = FXCollections.observableArrayList();
		if(rb.getId().equals("rAgv")){
			for(Map.Entry<Integer, Agv> m:main.agvMap.entrySet()){
				clientList.add(m.getValue());
			}
		}else if(rb.getId().equals("rMw")){
			for(Map.Entry<Integer, Park> m:main.parkMap.entrySet()){
				Park p = m.getValue();
				if(p.getType() == 1){
					clientList.add(m.getValue());
				}
			}
		}else if(rb.getId().equals("rFlow")){
			for(Map.Entry<Integer, Park> m:main.parkMap.entrySet()){
				Park p = m.getValue();
				if(p.getType() == 0){
					clientList.add(m.getValue());
				}
			}
		}else{
//			for(Map.Entry<Integer, Charger> m:main.chargerMap.entrySet()){
//				clientList.add(m.getValue());
//			}
		}
		client.setItems(clientList);
	}
}
